# -*- coding: utf-8 -*-
"""
 ----------------------------------------
|File Name:     sendEmail
|Author:        WYT
|date:          2020/6/10
 ----------------------------------------
|  Change Activity:
|                   2020/6/10:
-----------------------------------------
"""
import smtplib
import sys
from email.mime.text import MIMEText

from util.SingleMeta import SingleMeta
from util.g import g


class sendEmail(metaclass=SingleMeta):

    def __init__(self, subject, content, target="18235693860@163.com,54428404@qq.com"):
        """

        :param subject: 邮件名
        :param content: 邮件内容
        :param target: 收件人，有多个收件人时用逗号分隔
        """
        self.msg_from = "18235693860@163.com"
        self.password = "AUKTPORXURFYLYLO"
        self.sender = None
        self.get_sender()

        self.msg_to = target.split(",")
        self.subject = subject
        self.content = content

    def get_sender(self):
        try:
            self.sender = smtplib.SMTP_SSL("smtp.163.com", timeout=6)
            self.sender.connect("smtp.163.com")
        except Exception as err:
            msg = "{} err: {}".format(sys._getframe().f_code.co_name, err)
            if not g.logger:
                print(msg)
            else:
                g.logger.error(msg)

    def _login(self):
        while True:
            try:
                self.sender.login(self.msg_from, self.password)
            except smtplib.SMTPServerDisconnected as err:
                self.get_sender()
            else:
                break

    def _msg(self):
        self.msg = MIMEText(self.content, "plain", "utf-8")
        self.msg["Subject"] = self.subject
        self.msg["Form"] = self.msg_from
        self.msg["To"] = ",".join(self.msg_to)

    def send_mail(self):
        try:
            if self.content == None or self.content == "":
                pass
            else:
                self.__send_mail()
        except Exception as err:
            msg = "邮件内容: {} 发送邮件异常:{}".format(self.content, err)
            if not g.logger:
                print(msg)
            else:
                g.logger.error(msg)

    def __send_mail(self):
        try:
            self._login()
            self._msg()
            if not self.sender:
                return
            self.sender.sendmail(self.msg_from, self.msg_to, self.msg.as_string())
        except Exception as err:
            msg = "邮件发送失败, 原因: {} file_name: {} lines: {}".format(err, err.__traceback__.tb_frame.f_globals.get("__file__"), err.__traceback__.tb_lineno)
            if not g.logger:
                print(msg)
            else:
                g.logger.error(msg)
        else:
            msg = "邮件发送至 {} 成功!".format(self.msg_to)
            if not g.logger:
                print(msg)
            else:
                g.logger.info(msg)
        finally:
            self.sender.quit()
        # print(self.sender)


if __name__ == '__main__':
    a = sendEmail(subject="autoflow", content="发送邮件测试", target="18235693860@163.com")
    # for i in range(10):
    a.send_mail()
    # for i in range(10):
    #     a = sendEmail(subject="autoflow", content="发送邮件测试")
    #     print(id(a))
